package treeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class TreeNodeBottom {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> levelOrder = new LinkedList<List<Integer>>();
        if (root == null) {
            return levelOrder;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<Integer>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll(); //弹出
                level.add(node.val);
                TreeNode left = node.left, right = node.right;
                if (left != null) {
                    queue.offer(left);
                }
                if (right != null) {
                    queue.offer(right);
                }
            }
            levelOrder.add(0, level);
        }
        return levelOrder;
    }

    public static void main(String[] args) {
        TreeNodeBottom test= new TreeNodeBottom();
        List<List<Integer>> list = test.levelOrderBottom(TreeNodeUtils.getTestTreeNode());
        for (List<Integer> item:list){
            System.out.println(item);
        }
//        LinkedList<Integer> queue = new LinkedList<Integer>();  //队列，先进（offer)先出
//        queue.add(1);
//        queue.offer(2);
//        queue.offer(3);
//        queue.offer(4);
//        queue.add(5);
//        queue.addFirst(0);
//        System.out.println(queue);
//        System.out.println(queue.poll());
//        System.out.println(queue.poll());
//        System.out.println(queue);
    }
}
